package dispatcher;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import utils.MyBase64;

public class Message extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public Message()
	{
		
	}
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
	throws ServletException, IOException 
	{
		super.doGet(request, response);
	}	
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		HttpSession session = request.getSession(true);
		Object sessionUserID = session.getAttribute("userID");
		if(sessionUserID == null || sessionUserID.toString().trim().length() == 0)
		{
			response.sendRedirect("./login?option=" + MyBase64.encode(Login.NO_SESSION.getBytes()));
		}
		else
		{
			String type = request.getParameter("type");
			String msg = request.getParameter("msg");
			String formStatusID = request.getParameter("formStatusID");
			String elementID = request.getParameter("elementID");
			String pollStatusID = request.getParameter("pollStatusID");
			if(type != null && type.trim().length() > 0 && msg != null && msg.trim().length() > 0)
			{
				String typeDecoded = MyBase64.decodeToString(type);
				String msgDecoded = MyBase64.decodeToString(msg);
				request.setAttribute("typeMessage", typeDecoded);
				request.setAttribute("message", msgDecoded);
				if(formStatusID != null && formStatusID.trim().length() > 0 
						&& elementID != null && elementID.trim().length() > 0)
				{
					formStatusID = MyBase64.decodeToString(formStatusID);
					elementID = MyBase64.decodeToString(elementID);
					
					request.setAttribute("formStatusIDAtt", formStatusID);
					request.setAttribute("elementIDAtt", elementID);
				}
				if(pollStatusID != null && pollStatusID.trim().length() > 0)
				{
					pollStatusID = MyBase64.decodeToString(pollStatusID);
					request.setAttribute("pollStatusIDAtt", pollStatusID);
				}
				String page = "/messagePage.jsp";
				
				RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(page.toString());
				dispatcher.forward(request, response);
			}	
		}
	}
	
}
